<script lang="ts">
	import { onMount } from 'svelte';
	import { TableHandler, Datatable, ThSort, ThFilter } from '@vincjo/datatables';

	// 根据环境选择 API URL
	const API_URL = import.meta.env.DEV
		? import.meta.env.VITE_DEV_API_URL
		: import.meta.env.VITE_PROD_API_URL;

	let table: TableHandler<any>;
	let isLoading = true;
	let data: any[] = [];
	let isEditMode = false;
	let editingRow: any = null;
	let newRow = {
		code: '',
		spec: '',
		model: '',
		brand: '',
		location: '',
		qty: 0,
		created_at: '',
		updated_at: ''
	};

	// Code 格式处理函数
	function formatCode(code: string): string {
		// 如果为空，直接返回
		if (!code) return code;

		// 前3个字符转换为大写字母
		let prefix = code.slice(0, 3).toUpperCase();

		// 如果长度大于3，处理第4个字符
		if (code.length > 3) {
			// 如果第4个字符不是'.'，在前面添加'.'
			if (code[3] !== '.') {
				prefix += '.';
			}
			// 添加剩余部分
			prefix += code.slice(3);
		}

		return prefix;
	}

	// 处理 Code 输入
	function handleCodeInput(event: Event, isNewRow: boolean = true) {
		const input = event.target as HTMLInputElement;
		const value = input.value;

		// 只允许前3个字符为字母
		if (value.length <= 3) {
			if (!/^[a-zA-Z]*$/.test(value)) {
				input.value = value.replace(/[^a-zA-Z]/g, '');
			}
		}

		// 格式化 Code
		const formattedCode = formatCode(input.value);
		if (isNewRow) {
			newRow.code = formattedCode;
		} else if (editingRow) {
			editingRow.code = formattedCode;
		}
	}

	function handleNumberInput(event: Event, isNewRow: boolean = true) {
		const input = event.target as HTMLInputElement;
		const value = input.value;

		try {
			// Evaluate the mathematical expression
			const result = eval(value);
			input.value = result.toString();

			// Update the corresponding row
			if (isNewRow) {
				newRow.qty = result;
			} else if (editingRow) {
				editingRow.qty = result;
			}
		} catch (error) {
			console.error('Invalid mathematical expression:', error);
		}
	}

	onMount(handleGet);

	async function handleGet() {
		try {
			const resp = await fetch(API_URL + '/item');
			if (!resp.ok) {
				throw new Error('HTTP Error ! status: ${resp.status}');
			}
			const ack = await resp.json();
			console.log('API Response:', ack);
			// data = JSON.parse(ack.data);
			data = ack.data;
			console.log('Data after assignment:', data);
			table = new TableHandler(data, { rowsPerPage: 50 });
			table.createSort('updated_at').desc();
			console.log('Table after initialization:', table);
			console.log('Table rows:', table.rows);
		} catch (error) {
			console.error('failed to load data:', error);
		} finally {
			isLoading = false;
		}
	}
	async function handleSave() {
		try {
			// 只发送必要的字段，不包含时间戳
			const saveData = {
				code: newRow.code,
				spec: newRow.spec,
				model: newRow.model,
				brand: newRow.brand,
				location: newRow.location,
				qty: newRow.qty
			};

			const resp = await fetch(API_URL + '/item', {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json'
				},
				body: JSON.stringify(saveData)
			});

			if (!resp.ok) {
				throw new Error('Failed to save item');
			}

			// 重新加载数据
			await handleGet();

			// 重置新行数据
			newRow = {
				code: '',
				spec: '',
				model: '',
				brand: '',
				location: '',
				qty: 0,
				created_at: '',
				updated_at: ''
			};
		} catch (error) {
			console.error('Failed to save item:', error);
		}
	}

	async function handleUpdate(row: any) {
		try {
			// Ensure the quantity is a number before saving
			row.qty = Number(row.qty);

			const resp = await fetch(API_URL + '/item', {
				method: 'PUT',
				headers: {
					'Content-Type': 'application/json'
				},
				body: JSON.stringify(row)
			});

			if (!resp.ok) {
				throw new Error('Failed to update item');
			}

			// 重新加载数据
			await handleGet();

			// 退出编辑模式
			editingRow = null;
		} catch (error) {
			console.error('Failed to update item:', error);
		}
	}

	async function handleDelete(row: any) {
		try {
			// 如果 code 为空，则使用 model 字段
			const deleteData = row.code ? { code: row.code } : { model: row.model };

			const resp = await fetch(API_URL + '/item', {
				method: 'DELETE',
				headers: {
					'Content-Type': 'application/json'
				},
				body: JSON.stringify(deleteData)
			});

			if (!resp.ok) {
				throw new Error('Failed to delete item');
			}

			// 重新加载数据
			await handleGet();
		} catch (error) {
			console.error('Failed to delete item:', error);
		}
	}

	function startEdit(row: any) {
		editingRow = { ...row };
	}

	function cancelEdit() {
		editingRow = null;
	}

	function copyRow(row: any) {
		// 复制行数据，但清空编码（因为编码需要唯一）
		newRow = {
			code: '',
			spec: row.spec,
			model: row.model,
			brand: row.brand,
			location: row.location,
			qty: row.qty,
			created_at: '',
			updated_at: ''
		};
		// 自动进入编辑模式
		isEditMode = true;
	}
</script>

{#if !isLoading}
	<div class="p-4">
		<div class="flex justify-between items-center mb-4">
			<button
				class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded"
				onclick={() => (isEditMode = !isEditMode)}
			>
				{isEditMode ? '退出编辑' : '进入编辑'}
			</button>
		</div>

		<Datatable basic {table}>
			<table class="min-w-full bg-white border border-gray-300">
				<thead>
					<tr>
						<ThSort {table} field="code">编码</ThSort>
						<ThSort {table} field="spec">规格</ThSort>
						<ThSort {table} field="model">型号</ThSort>
						<ThSort {table} field="brand">品牌</ThSort>
						<ThSort {table} field="location">位置</ThSort>
						<ThSort {table} field="qty">数量</ThSort>
						<ThSort {table} field="created_at">创建时间</ThSort>
						<ThSort {table} field="updated_at">更新时间</ThSort>
						{#if isEditMode}
							<th>操作</th>
						{/if}
					</tr>
				</thead>
				<tbody>
					{#if isEditMode}
						<tr class="bg-gray-50">
							<td>
								<input
									type="text"
									bind:value={newRow.code}
									oninput={(e) => handleCodeInput(e, true)}
									class="w-full px-2 py-1 border rounded"
									placeholder="输入编码 (前3位字母)"
									maxlength="10"
								/>
							</td>
							<td>
								<input
									type="text"
									bind:value={newRow.spec}
									class="w-full px-2 py-1 border rounded"
									placeholder="输入规格（可为空）"
								/>
							</td>
							<td>
								<input
									type="text"
									bind:value={newRow.model}
									class="w-full px-2 py-1 border rounded"
									placeholder="输入型号"
								/>
							</td>
							<td>
								<input
									type="text"
									bind:value={newRow.brand}
									class="w-full px-2 py-1 border rounded"
									placeholder="输入品牌"
								/>
							</td>
							<td>
								<input
									type="text"
									bind:value={newRow.location}
									class="w-full px-2 py-1 border rounded"
									placeholder="输入位置"
								/>
							</td>
							<td>
								<input type="number" bind:value={newRow.qty} />
							</td>
							<td>
								<button
									class="bg-green-500 hover:bg-green-600 text-white px-2 py-1 rounded"
									onclick={handleSave}
								>
									新增
								</button>
							</td>
						</tr>
					{/if}
					{#each table.rows as row}
						<tr class="hover:bg-gray-50">
							{#if editingRow && editingRow.model === row.model}
								<td>
									<input
										type="text"
										bind:value={editingRow.code}
										oninput={(e) => handleCodeInput(e, false)}
										class="w-full px-2 py-1 border rounded"
										placeholder="输入编码 (前3位字母)"
										maxlength="10"
									/>
								</td>
								<td>
									<input
										type="text"
										bind:value={editingRow.spec}
										class="w-full px-2 py-1 border rounded"
									/>
								</td>
								<td>
									<input
										type="text"
										bind:value={editingRow.model}
										class="w-full px-2 py-1 border rounded"
									/>
								</td>
								<td>
									<input
										type="text"
										bind:value={editingRow.brand}
										class="w-full px-2 py-1 border rounded"
									/>
								</td>
								<td>
									<input
										type="text"
										bind:value={editingRow.location}
										class="w-full px-2 py-1 border rounded"
									/>
								</td>
								<td>
									<input
										type="text"
										bind:value={editingRow.qty}
										oninput={(e) => handleNumberInput(e, false)}
										class="w-full px-2 py-1 border rounded"
									/>
								</td>
								<td class="whitespace-nowrap">
									<div class="flex gap-1">
										<button
											class="bg-green-500 hover:bg-green-600 text-white px-1 py-1 rounded text-xs"
											onclick={() => handleUpdate(editingRow)}
											title="保存"
										>
											保存
										</button>
										<button
											class="bg-gray-500 hover:bg-gray-600 text-white px-1 py-1 rounded text-xs"
											onclick={cancelEdit}
											title="取消"
										>
											取消
										</button>
									</div>
								</td>
							{:else}
								<td>{row.code}</td>
								<td>{row.spec}</td>
								<td>{row.model}</td>
								<td>{row.brand}</td>
								<td>{row.location}</td>
								<td>{row.qty}</td>
								<td>{row.created_at}</td>
								<td>{row.updated_at}</td>
								{#if isEditMode}
									<td class="whitespace-nowrap">
										<div class="flex gap-1">
											<button
												class="bg-blue-500 hover:bg-blue-600 text-white px-1 py-1 rounded text-xs"
												onclick={() => startEdit(row)}
												title="编辑"
											>
												编辑
											</button>
											<button
												class="bg-yellow-500 hover:bg-yellow-600 text-white px-1 py-1 rounded text-xs"
												onclick={() => copyRow(row)}
												title="复制"
											>
												复制
											</button>
											<button
												class="bg-red-500 hover:bg-red-600 text-white px-1 py-1 rounded text-xs"
												onclick={() => handleDelete(row)}
												title="删除"
											>
												删除
											</button>
										</div>
									</td>
								{/if}
							{/if}
						</tr>
					{/each}
				</tbody>
			</table>
		</Datatable>
	</div>
{/if}
